package com.cn.intelligence.controller;

import com.cn.intelligence.bean.Md5;
import com.cn.intelligence.pojo.EUDataGridResult;
import com.cn.intelligence.pojo.TaotaoResult;
import com.cn.intelligence.pojo.TbMUser;
import com.cn.intelligence.pojo.TbVideo;
import com.cn.intelligence.service.VideoService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

import java.io.*;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/video/")
public class VideoController {
    @Autowired
    private VideoService service;

    @Autowired
    private Md5 md5;

    private String getExtName(MultipartFile file) {
        String result = "";
        int index = file.getOriginalFilename().lastIndexOf(".");
        if (index >= 0) {
            result = file.getOriginalFilename().substring(index);
        }

        return result;
    }

    private String getMd5Path(MultipartFile file) throws Exception {
        String md5String = md5.md5MultipartFile(file);
        return  "/" + md5String.substring(0, 2) + "/" + md5String.substring(2, 4) + "/" + md5String + getExtName(file);
    }

    private boolean writeVideoFile(MultipartFile uploadFile, String path) throws IOException {
        File file = new File(path);
        if (!file.getParentFile().isDirectory()) {
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }

        InputStream fis = uploadFile.getInputStream();
        FileOutputStream fos = new FileOutputStream(file, false);
        byte[] data = new byte[2048];
        int len;

        while (-1 != (len = fis.read(data, 0, 2048))) {
            fos.write(data, 0, len);
        }

        // @todo 异常处理先忽略
        fis.close();
        fos.close();

        return true;
    }

    private Long getAdminId(HttpServletRequest request) {
        TbMUser user = (TbMUser)request.getSession().getAttribute("user");
        if (user != null) {
            return user.getId();
        }

        return 0l;
    }

    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public TaotaoResult saveVideo(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        String title = paramMap.get("title");
        String description = paramMap.get("description");
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("uploadFile");
        if (null == file || file.isEmpty()) {
            return TaotaoResult.fail();
        }
        String path;
        try {
            path = getMd5Path(file);
            if (!writeVideoFile(file, service.getVideoPath() + path)) {
                return TaotaoResult.fail();
            }

            TbVideo video = new TbVideo();
            video.setPath(path);
            video.setTitle(title);
            video.setDescription(description);
            video.setAdminCreateIp(request.getRemoteAddr());
            video.setAdminCreateTime(new Date());
            video.setAdminUid(getAdminId(request).intValue());
            if (!service.addVideo(video)) {
                return TaotaoResult.fail();
            }
        } catch (Exception ex) {
            return TaotaoResult.fail();
        }

        return TaotaoResult.ok("ok");
    }

    @ResponseBody
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public TaotaoResult getVideo(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        String strId = paramMap.get("id");
        int id;
        try {
            id = Integer.parseInt(strId);
        } catch (NumberFormatException ex) {
            return TaotaoResult.fail();
        }

        TbVideo result = service.selectById(id);
        result.setPath(service.getVideoServer() + result.getPath());
        return TaotaoResult.ok(result);
    }

    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public TaotaoResult delete(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        String strId = paramMap.get("id");
        int id;
        try {
            id = Integer.parseInt(strId);
        } catch (NumberFormatException ex) {
            return TaotaoResult.fail();
        }

        return TaotaoResult.ok(service.deleteVideo(id));
    }

    @ResponseBody
    @RequestMapping(value = "getAll", method = RequestMethod.GET)
    public EUDataGridResult getAll(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        EUDataGridResult result = new EUDataGridResult();
        String strPage = paramMap.get("page");
        String strPageSize = paramMap.get("rows");
        int page,pageSize;
        try {
            page = Integer.parseInt(strPage);
            pageSize = Integer.parseInt(strPageSize);
        } catch (NumberFormatException ex) {
            return result;
        }

        PageInfo<TbVideo> pageInfo = service.selectAll(page, pageSize);
        result.setRows(pageInfo.getList());
        result.setTotal(pageInfo.getTotal());
        return result;
    }
}
